package com.ugoodtech.mdcc.web.controller;

import com.ugoodtech.mdcc.core.domain.User;
import com.ugoodtech.mdcc.core.exception.VStarException;
import com.ugoodtech.mdcc.web.dto.JsonException;
import com.ugoodtech.mdcc.web.dto.JsonResponse;
import com.ugoodtech.mdcc.web.dto.LabelValue;
import com.ugoodtech.mdcc.web.service.UserLogService;
import org.hibernate.HibernateException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Copyright © 2013 All Rights Reserved, Ugood Technology, LLC.
 * <p/>
 * User: Stone
 */
@ApiIgnore
public class BaseController {
//    @Value("${logger.skip}")
//    public Boolean loggerSkip;

    public static final Logger log = LoggerFactory.getLogger(BaseController.class);


    boolean test = false;

    @Autowired
    public UserLogService userLogService;

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public JsonResponse resolveException(HttpServletRequest req, HttpServletResponse resp, Exception exp) {
        JsonResponse jsonResponse = new JsonResponse();
        if (exp instanceof JsonException) {
            jsonResponse.setSuccess(true);
            jsonResponse.setErrorDescription(exp.getMessage());
            if (((JsonException) exp).getErrCode() != null) {
                jsonResponse.setError(((JsonException) exp).getErrCode());
            }
            resp.setStatus(HttpServletResponse.SC_OK);
//            exp.printStackTrace();
        } else if (exp instanceof HibernateException || exp instanceof VStarException) {
            jsonResponse.setSuccess(false);
            jsonResponse.setErrorDescription(exp.getMessage());
            resp.setStatus(HttpServletResponse.SC_OK);
            exp.printStackTrace();
        } else {
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            jsonResponse.setSuccess(false);
            jsonResponse.setErrorDescription(exp.getMessage());
            exp.printStackTrace();
        }
        return jsonResponse;
    }

    protected User getCurrentUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Object principal = authentication.getPrincipal();
        if (principal != null && principal instanceof User) {
            return (User) principal;
        } else {
            Object details = authentication.getDetails();
            if (details != null && details instanceof User) {
                return (User) details;
            }
        }
        return null;
    }

    public void isUserLogin() {
        if (!test && null == this.getCurrentUser()) {
            throw new JsonException("notLogin");
        }
    }


    public Date StringToDate(String dateString) {
        if (null != dateString && !"".equals(dateString) && !dateString.equals("null")) {
            String dateAll = dateString.split("T")[0];
            String yyyy = dateAll.split("-")[0];
            String MM = dateAll.split("-")[1];
            String dd = dateAll.split("-")[2];
            DateFormat dateFormat = new java.text.SimpleDateFormat("yyyyMMdd");
            Date date = null;
            try {
                date = dateFormat.parse(yyyy + MM + dd);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            return date;
        } else {
            return null;
        }
    }

    public List<LabelValue> getLabelValueListForString(List<LabelValue> labelValues, Boolean addAll) {
        List<LabelValue> dataList = new ArrayList<>();
        if (null != addAll && addAll) {
            dataList.add(new LabelValue("不限", null));
        }
        for (LabelValue labelValue : labelValues) {
            dataList.add(labelValue);
        }

        return dataList;
    }

    public List<String[]> getLabelValueArrayForString(List<LabelValue> labelValues, Boolean addAll) {
        List<String[]> dataList = new ArrayList<String[]>();
        if (null != addAll && addAll) {
            dataList.add(new String[]{null, "不限"});
        }
        for (LabelValue labelValue : labelValues) {
            dataList.add(new String[]{labelValue.getValue(), labelValue.getLabel()});
        }

        return dataList;
    }

    public List<String[]> getLabelValueArrayForLong(List<LabelValue> labelValues, Boolean addAll) {
        List<String[]> dataList = new ArrayList<String[]>();
        if (null != addAll && addAll) {
            dataList.add(new String[]{null, "All"});
        }
        for (LabelValue labelValue : labelValues) {
            dataList.add(new String[]{labelValue.getValue(), labelValue.getLabel()});
        }

        return dataList;
    }

    public List<String[]> getZeroLabelValueArrayForLong(List<LabelValue> labelValues, Boolean addAll) {
        List<String[]> dataList = new ArrayList<String[]>();
        if (null != addAll && addAll) {
            dataList.add(new String[]{null, "All"});
            dataList.add(new String[]{"0", "0"});
        }
        for (LabelValue labelValue : labelValues) {
            dataList.add(new String[]{labelValue.getValue(), labelValue.getLabel()});
        }

        return dataList;
    }

    public Float parseFloat(String number) {
        try {
            return Float.valueOf(number);
        } catch (NumberFormatException e) {
            e.printStackTrace();
            return null;
        }
    }

    public Double parseDouble(String number) {
        try {
            return Double.valueOf(number);
        } catch (NumberFormatException e) {
            e.printStackTrace();
            return null;
        }
    }


    public Integer valueOf(String number) {
        try {
            return Integer.valueOf(number);
        } catch (NumberFormatException e) {
            e.printStackTrace();
            return null;
        }
    }

    public void debugException(String methodName, Exception e, Logger logger) {
        logger.debug(methodName + e.toString());
        if (null != e.getStackTrace()) {
            if (e.getStackTrace().length != 0) {
                for (StackTraceElement stackTraceElement : e.getStackTrace()) {
                    logger.debug("at " + stackTraceElement);
                }
            }
        }
    }
}
